package day240515.e1_my;

import java.lang.reflect.Field;

public class MySortUtil {

    public static void print(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void print(MyComparable[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void sort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            boolean swapped = false;
            for (int j = 0; j < (arr.length - 1) - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }
            if (!swapped) {
                break;
            }
        }
    }

    public static void sort(MyComparable[] arr, String fieldName) throws NoSuchFieldException, IllegalAccessException {
        Field field = arr[0].getClass().getDeclaredField(fieldName);
        field.setAccessible(true);

        for (int i = 0; i < arr.length - 1; i++) {
            boolean swapped = false;
            for (int j = 0; j < (arr.length - 1) - i; j++) {
                Object field1 = field.get(arr[j]);
                Object field2 = field.get(arr[j + 1]);

                if (field.getType() == String.class) {
                    String s1 = (String) field1;
                    String s2 = (String) field2;
                    if (s1.compareTo(s2) < 0) {
                        MyComparable temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                        swapped = true;
                    }
                }

                if (field.getType() == int.class) {
                    if ((int) field1 > (int) field2) {
                        MyComparable temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                        swapped = true;
                    }
                }

                if (field.getType() == double.class) {
                    if ((double) field1 > (double) field2) {
                        MyComparable temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                        swapped = true;
                    }
                }

            }
            if (!swapped) {
                break;
            }
        }
    }
}
